// 导入uni-id-common模块和数据库
// 在uniCloud环境中正确引用uni-id-common模块
const uniID = require('uni-id-common');
// 使用相对路径引用uni_modules中的模块
const createConfigCenter = require('../../../uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/index.js');
const db = uniCloud.database();
const _ = db.command;

/**
 * 获取动态列表数据
 * @param {Object} event 客户端传入的参数
 * @param {String} event.token 用户token
 * @param {String} event.category 分类：recommend(推荐)/follow(关注)/latest(最新)
 * @param {Number} event.pageNum 页码，默认为1
 * @param {Number} event.pageSize 每页数量，默认为10
 * @param {Object} context 上下文信息
 */
exports.main = async (event, context) => {
  // 支持两种参数名：category和type
  const { token, category = event.type || 'recommend', pageNum = 1, pageSize = 10 } = event;
  
  // 初始化配置中心
  const config = createConfigCenter({ pluginId: 'uni-id' });
  const uniIdConfig = config.config();
  
  // 初始化uniID实例
  const uniIDIns = uniID.createInstance({
    context,
    config: uniIdConfig
  });
  
  // 解析页码和每页数量
  const page = parseInt(pageNum) || 1;
  const size = parseInt(pageSize) || 10;
  const skip = (page - 1) * size;
  
  // 检查并验证token
  let currentUserId = null;
  if (token) {
    try {
      const checkTokenRes = await uniIDIns.checkToken(token);
      if (!checkTokenRes.code) {
        currentUserId = checkTokenRes.uid;
      }
    } catch (error) {
      console.error('token验证失败:', error);
    }
  }
  
  try {
    // 为了测试，添加临时mock数据 - 调整为前端期望的数据结构
    const mockPosts = [
      {
        id: 'mock-1',  // 前端使用id而不是_id
        user: {
          name: '测试用户1',  // 前端使用name而不是nickname
          avatar: 'https://cn.bing.com/images/search?view=detailV2&ccid=f1Vh%2bzDA&id=D46703B9F54A7E96C102119894888379FF358C9C&thid=OIP.f1Vh-zDACSQXc7-TuwT_ZwHaHa&mediaurl=https%3a%2f%2fimg.shetu66.com%2f2023%2f04%2f25%2f1682391070981336.png&exph=1024&expw=1024&q=%e5%9b%be%e7%89%87&FORM=IRPRST&ck=5F0083E4E1D06FF8540FE2B930E32F42&selectedIndex=65&itb=0'
        },
        content: '这是一条测试动态内容，用于测试前端显示效果。',
        images: [],
        time: '刚刚',  // 前端需要格式化的时间
        likes: 10,  // 前端使用likes而不是likeCount
        comments: 5,  // 前端使用comments而不是commentCount
        isLiked: false
      },
      {
        id: 'mock-2',
        user: {
          name: '测试用户2',
          avatar: 'https://cn.bing.com/images/search?view=detailV2&ccid=Mq9zt66l&id=554BA9BB025216F1FBDE6FEB4EF8DFB2DF994341&thid=OIP.Mq9zt66lU2fko_h2OWHIlAHaE8&mediaurl=https%3a%2f%2fts1.tc.mm.bing.net%2fth%2fid%2fR-C.32af73b7aea55367e4a3f8763961c894%3frik%3dQUOZ37Lf%252bE7rbw%26riu%3dhttp%253a%252f%252fimg95.699pic.com%252fphoto%252f50064%252f7148.jpg_wh860.jpg%26ehk%3d00VUYvoTnuinFTJXQYbpLwh3e%252bLPJE9vL7h5ELm0avA%253d%26risl%3d%26pid%3dImgRaw%26r%3d0&exph=574&expw=860&q=%e5%9b%be%e7%89%87&FORM=IRPRST&ck=2E848027E816A281546868712B2E7A19&selectedIndex=4&itb=0'
        },
        content: '这是第二条测试动态，包含测试图片。',
        images: ['https://ts1.tc.mm.bing.net/th/id/R-C.987f582c510be58755c4933cda68d525?rik=C0D21hJDYvXosw&riu=http%3a%2f%2fimg.pconline.com.cn%2fimages%2fupload%2fupc%2ftx%2fwallpaper%2f1305%2f16%2fc4%2f20990657_1368686545122.jpg&ehk=netN2qzcCVS4ALUQfDOwxAwFcy41oxC%2b0xTFvOYy5ds%3d&risl=&pid=ImgRaw&r=0'],
        time: '1小时前',
        likes: 15,
        comments: 8,
        isLiked: true
      }
    ];
    
    // 直接返回mock数据用于测试
    return {
      code: 0,
      message: '获取动态列表成功',
      data: {
        list: mockPosts,
        hasMore: false,
        total: mockPosts.length,
        page: page,
        pageSize: size
      }
    };
    
    /* 实际数据库查询代码（暂时注释掉）
    const dynamicCollection = db.collection('dynamic_posts');
    let query = {};
    
    // 根据分类构建查询条件
    switch (category) {
      case 'follow':
        // 关注分类：需要先获取用户关注的列表
        if (!currentUserId) {
          return {
            code: 1,
            message: '关注列表需要登录后查看',
            data: []
          };
        }
        
        // 查询用户关注的人
        const followsRes = await db.collection('user_follows')
          .where({
            userId: currentUserId
          })
          .field({
            followId: true
          })
          .get();
        
        const followIds = followsRes.data.map(item => item.followId);
        
        if (followIds.length === 0) {
          return {
            code: 0,
            message: '暂无关注动态',
            data: [],
            total: 0
          };
        }
        
        query.userId = _.in(followIds);
        // 同时查询公开和关注可见的动态
        query.privacy = _.in(['public', 'followers']);
        break;
        
      case 'latest':
        // 最新分类：仅查询公开动态
        query.privacy = 'public';
        break;
        
      case 'recommend':
      default:
        // 推荐分类：默认查询公开动态，后续可以加入推荐算法
        query.privacy = 'public';
        break;
    } */
    
    // 构建基础查询
    let dbQuery = dynamicCollection.where(query);
    
    // 排序方式
    let orderBy = {};
    switch (category) {
      case 'recommend':
        // 推荐分类可以根据点赞数、评论数等综合排序，这里简单按创建时间倒序
        orderBy = { createTime: -1 };
        break;
        
      case 'latest':
        // 最新分类按创建时间倒序
        orderBy = { createTime: -1 };
        break;
        
      case 'follow':
        // 关注分类按创建时间倒序
        orderBy = { createTime: -1 };
        break;
    }
    
    // 查询总数
    const totalRes = await dbQuery.count();
    const total = totalRes.total;
    
    // 查询分页数据
    const postsRes = await dbQuery
      .orderBy(Object.keys(orderBy)[0], Object.values(orderBy)[0])
      .skip(skip)
      .limit(size)
      .get();
    
    let posts = postsRes.data;
    
    // 如果用户已登录，检查用户是否点赞了这些动态
    if (currentUserId && posts.length > 0) {
      const postIds = posts.map(post => post._id);
      
      // 查询用户点赞记录
      const likesRes = await db.collection('post_likes')
        .where({
          userId: currentUserId,
          postId: _.in(postIds)
        })
        .get();
      
      // 构建已点赞的动态ID集合
      const likedPostIds = new Set(likesRes.data.map(like => like.postId));
      
      // 更新动态的点赞状态
      posts = posts.map(post => ({
        ...post,
        isLiked: likedPostIds.has(post._id)
      }));
    }
    
    return {
      code: 0,
      message: '获取动态列表成功',
      data: {
        list: posts,
        hasMore: skip + posts.length < total,
        total: total,
        page: page,
        pageSize: size
      }
    };
  } catch (error) {
    console.error('获取动态列表失败:', error);
    return {
      code: 1,
      message: '获取动态列表失败',
      data: error.message
    };
  }
};